package com.jackstraw.jack_base.remote_command.aop;

import com.jackstraw.jack_base.remote_command.entity.Conn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Slf4j
@Aspect
@Component
public class JschServiceAop {
    @Pointcut(" execution(* com.jackstraw.jack_base.remote_command.service.JschService.*(..))")
    public void exceptionPointcut() {

    }

    // 配置环绕通知,使用在方法aspect()上注册的切入点
    @Around("exceptionPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();// 获得目标方法名
        String className = joinPoint.getSignature().getDeclaringTypeName();//目标全路径
        Object[] args = joinPoint.getArgs();
        Assert.notNull(args, className + "#" + methodName + "入参为空");
        Object arg = args[0];
        Conn conn = null;
        if (arg instanceof Conn && ObjectUtils.isNotEmpty(arg)) {
            conn = (Conn) arg;
        }
        log.info("AOP 环绕通知<============={}#{}方法执行开始,连接名称为:{}=============>", className, methodName, conn.getConnName());
        long start = System.currentTimeMillis();
        Object result = null;
        try {
            result = joinPoint.proceed(args);
        } finally {
            conn.close();
        }
        long end = System.currentTimeMillis();
        log.info("AOP 环绕通知<============={}#{}方法执行结束，连接名称为:{},执行{}Millis=============>", className, methodName, conn.getConnName(), (end - start));
        return result;
    }
}
